//
//  CAAddressViewController.m
//  LNH
//
//  Created by twentylx on 2018/1/29.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAAddressViewController.h"
#import "CAAddressTableViewCell.h"
#import "CANewAddressViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "CAAddressApi.h"
#import "CASetDefaultAddressApi.h"
#import "CADelAddressApi.h"

@interface CAAddressViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *addressTableView;
@property (nonatomic, strong) NSArray *addressArray;
@property (nonatomic, strong) UIButton *newButton;

@end

static NSString *cellIdentifier = @"addressCell";

@implementation CAAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
    
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.addressTableView];
    [self.view addSubview:self.newButton];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.title = @"收货地址";
}

#pragma mark layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    [_addressTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.newButton.mas_top);
    }];
    
    [_newButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
       
        if (isIPhoneX) {
             make.bottom.equalTo(self.view).offset(-34);
        } else {
             make.bottom.equalTo(self.view);
        }
        make.height.mas_equalTo(44);
    }];
}

#pragma mark get & set
- (UITableView *)addressTableView {
    if (!_addressTableView) {
        _addressTableView = [UITableView new];
        _addressTableView.backgroundColor = RGBCOLOR(241, 241, 241);
        _addressTableView.dataSource = self;
        _addressTableView.delegate = self;
        _addressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_addressTableView registerClass:[CAAddressTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    }
    return _addressTableView;
}

- (UIButton *)newButton {
    if (!_newButton) {
        _newButton = [UIButton new];
        [_newButton setTitle:@"添加收货地址" forState:UIControlStateNormal];
        _newButton.backgroundColor = RGBCOLOR(233, 85, 19);
        _newButton.titleLabel.font = [UIFont systemFontOfSize:20];
        
        [[_newButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CANewAddressViewController *newAddressVC = [CANewAddressViewController new];
            [self.navigationController pushViewController:newAddressVC animated:YES];
        }];
    }
    return _newButton;
}

#pragma mark private method
- (void) loadData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CAAddressApi *addressApi = [[CAAddressApi alloc] init];
    [addressApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAAddressApi *api = (CAAddressApi *) request;
        if (api.done) {
            self.addressArray = api.responseObject[@"result"];
            [self.addressTableView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) setDefaultAddressWithAddressId:(NSString *) addressId {
    CASetDefaultAddressApi *setDefaultApi = [[CASetDefaultAddressApi alloc] initWithAddressId:addressId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [setDefaultApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CASetDefaultAddressApi *api = (CASetDefaultAddressApi *) request;
        if (api.done) {
            [self loadData];
        } else {
            [SVProgressHUD showErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) delAddressWithAddressId:(NSString *) addressId {
    CADelAddressApi *delApi = [[CADelAddressApi alloc] initWithAddressId:addressId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [delApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CADelAddressApi *api = (CADelAddressApi *) request;
        if (api.done) {
            [self.addressTableView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CAAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    NSDictionary *dict = _addressArray[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.nameLabel.text = dict[@"name"];
    cell.phoneLabel.text = dict[@"phone_number"];
    cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",dict[@"province_name"], dict[@"city_name"], dict[@"area_name"], dict[@"address"]];
    
    BOOL isDefault = [dict[@"is_default"] boolValue];
    if (isDefault) {
        cell.defaultButton.selected = YES;
    } else {
        cell.defaultButton.selected = NO;
    }
    
    //设为默认
    [[[cell.defaultButton rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self setDefaultAddressWithAddressId:dict[@"id"]];
    }];
    //删除
    [[[cell.delButton rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self delAddressWithAddressId:dict[@"id"]];
    }];
    
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = self.addressArray[indexPath.row];
    if ([self.delegate respondsToSelector:@selector(selectAddressWithDict:)]) {
        [self.delegate selectAddressWithDict:dict];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
//        CADelBankCardViewController *delVC = [CADelBankCardViewController new];
//        delVC.cardId = [NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]];
//        delVC.cardNo = dict[@"card_number"];
//        [self.navigationController pushViewController:delVC animated:YES];
    }
    
}


@end
